import React,{useState} from "react";
import {View,Text,StyleSheet,TextInput,PixelRatio,Platform,PermissionsAndroid,Image,ScrollView} from "react-native";
import { windowHeight,windowWidth,getWidth} from "@/utils/index";
import Touchable from "../../components/Touchable";
import {connect, ConnectedProps} from 'react-redux';
import {RootState} from '@/models/index';
import  { launchCamera ,  launchImageLibrary }  from  'react-native-image-picker' ;
import Toast from 'react-native-root-toast';

interface IFormData {
  artical_title:any;
  artical_detail:any;
  // publish_time:any;
  type:"video" | "image";
  // 文章的所属者就是当前用户
  owner_id:string;
}
interface IProps extends ModelState {
  navigation: {goBack: any; navigate: any};
  route: any;
}

const mapStateToProps = ({users, loading}: RootState) => {
  return {
    // 在触发getUserInfo方法时加上加载效果
    loading: loading.effects['users/addAddress'],
  };
};
const connector = connect(mapStateToProps);
type ModelState = ConnectedProps<typeof connector>;
const AddArtical = (props:IProps) => {
  const {route,dispatch,navigation} = props;
  const [images, setImages] = useState<any[]>([]);
  const [formData,setFormData] = useState<IFormData>({
    artical_title:null,
    artical_detail:null,
    // publish_time:null,
    type:"image",
    // 文章的所属者就是当前用户
    owner_id:route.params.user_id
  });
  const handleAddArtical = () => {
    if (!formData.artical_title) {
      Toast.show('必须填写文章标题', {
        position: Toast.positions.CENTER,
        duration: Toast.durations.LONG,
        shadow: true,
        animation: true,
      });
      return;
    }
    if (!formData.artical_detail) {
      Toast.show('必须填写文章内容', {
        position: Toast.positions.CENTER,
        duration: Toast.durations.LONG,
        shadow: true,
        animation: true,
      });
      return;
    }
    if (JSON.stringify(images) === "[]") {
      Toast.show('必须上传文件', {
        position: Toast.positions.CENTER,
        duration: Toast.durations.LONG,
        shadow: true,
        animation: true,
      });
      return;
    }
    console.log("发布文章",formData);
    console.log("images",images);
    let newFormData = Object.assign(formData,{
      images:images
    })
    console.log("newFormData",newFormData)
    dispatch({
      type: 'articals/addArtical',
      payload: {
        formData:newFormData,
        callback: () => {
          console.log("route.params.handleClick",route.params.handleClick)
          route.params.handleClick && route.params.handleClick()
            Toast.show('发布成功', {
                position: Toast.positions.CENTER,
                duration: Toast.durations.LONG,
                shadow: true,
                animation: true,
              });
          navigation.navigate("Circle")
        },
      },
    });
   
  }
  const onChangeText = (text: string, name: string) => {
    console.log('name1111111111111', name, 'text111111111111111111', text);
    let obj = {[name]: text};
    let newFormData = Object.assign(formData, obj);
    console.log("newFormData",newFormData);
    setFormData(newFormData);
  };
  const handleRadio = (type:"video"|"image") => {
    let newFormData:IFormData = {
      ...formData,
      type:type,
    };
    setFormData(newFormData);
  };
  const handleSubmitFile = () => {
    const options: any = {
      cameraType: 'back',
      mediaType: 'photo', // 媒体类型还可以是视频或者图片视频二者混合，默认选取一张
      videoQuality: 'high',
      durationLimit: 10,
      maxWidth: 720,
      maxHeight: 1280,
      quality: 1,
      // 允许选择多张
      // multiple: true, // 设置为true，可以选择多张图片
      selectionLimit:0
    };
    async function requestCameraPermission() {
      console.log("Platform.Version",Platform.Version)
      if (Platform.Version as number >= 31) {
        // 如果运行的是 Android 12 或更高版本，选用新模型来请求相机权限
        // const result = await requestPermissionAndroid12('android.permission.CAMERA');
        // 请求本地存储权限
        const result = await requestPermissionAndroid12('android.permission.READ_EXTERNAL_STORAGE')
        if (result === PermissionsAndroid.RESULTS.GRANTED) {
          console.log("加载权限")
          // launchCamera(options, (res)=>{
          //   console.log("res",res)
          // });
          //打开图库
          launchImageLibrary(options, ({assets})=>{
            console.log("res1111111111111111111111",assets)
            // res {"assets": [{"fileName": "rn_image_picker_lib_temp_00144087-1f0f-4d10-ae39-5ad9f2a02440.jpg", "fileSize": 232251, "height": 720, "type": "image/jpeg", "uri": "file:///data/user/0/com.xipai/cache/rn_image_picker_lib_temp_00144087-1f0f-4d10-ae39-5ad9f2a02440.jpg", "width": 720}]}
            if(assets) {
              setImages(assets)
            }
          });
          console.log('Camera permission granted权限通过');
        } else {
          console.log('Camera permission denied权限拒绝');
        }
      } else {
        // 如果运行的是 Android 11 或更低版本，使用之前的版本的权限请求模型来请求
        try {
          const granted = await PermissionsAndroid.request(
            // PermissionsAndroid.PERMISSIONS.CAMERA,
            PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
            {
              title: 'App android.permission.READ_EXTERNAL_STORAGE Permission',
              message: 'App needs access to android.permission.READ_EXTERNAL_STORAGE.',
              buttonNeutral: 'Ask Me Later',
              buttonNegative: 'Cancel',
              buttonPositive: 'OK',
            },
          );
          if (granted === PermissionsAndroid.RESULTS.GRANTED) {
            console.log('Camera permission granted,11一下权限请求通过');
          } else {
            console.log('Camera permission denied,11一下权限请求失败');
          }
        } catch (err) {
          console.warn(err);
        }
      }
    }
    async function requestPermissionAndroid12(permission:any) {
      // 检查是否该应用被永久允许了相机权限android.permission.CAMERA
      const isGranted = await PermissionsAndroid.check(permission);
      if (isGranted) {
        // 如果设置的应用权限管理中用户允许了，直接返回许可令
        return PermissionsAndroid.RESULTS.GRANTED;
      }
      // 询问用户是否给权限，如果用户设置的是每次使用时询问
      const result = await PermissionsAndroid.request(permission);
      if (result === PermissionsAndroid.RESULTS.GRANTED) {
        console.log("yunxu")
        return PermissionsAndroid.RESULTS.GRANTED;
      } else if (result === PermissionsAndroid.RESULTS.NEVER_ASK_AGAIN) {
        throw new Error('Permission denied with never ask again');
      } else {
        throw new Error('Permission denied');
      }
    }
    
   
    requestCameraPermission()
  }
  return (
    <View style={styles.addArtical}>
       <ScrollView>
      <View style={styles.mainBox}>
        <View>
          <Text style={styles.label}>文章标题：</Text>
          <TextInput
            placeholder="请输入文章标题"
            style={[styles.inputBox, styles.inputBoxTop]}
            onChangeText={text =>
              onChangeText(text, 'artical_title')
            }></TextInput>
        </View>
        <View>
          <Text style={styles.label}>文章内容：</Text>
          <TextInput
            placeholder="请输入文章内容"
            style={[styles.inputBox, styles.inputBoxTop, styles.manyLines]}
            onChangeText={text => onChangeText(text, 'artical_detail')}
            multiline={true}
            numberOfLines={8}></TextInput>
        </View>
      
       <Touchable style={styles.addBox} onPress={handleSubmitFile}>
       {
        JSON.stringify(images) === "[]" && (
          <View style={styles.file} >
          <Text style={styles.label}>上传文件：</Text>
              <Image
              source={require('../../assets/localImage/add2.png')}
              style={styles.addpng}></Image>
        </View>
        )
      }
        {JSON.stringify(images) !== '[]' && (
            <View style={styles.selectImageBox}>
              <Text style={styles.text}>图片或者视频文件</Text>
              <View style={styles.imageBox}>
              {images.map(i => {
                return (
                  <Image source={{uri: i.uri}} style={styles.avatarImage} key={i.fileName}/>
                );
              })}
            </View>
            </View>
          )}
        </Touchable>
     
        <View style={styles.radioBox}>
        <Touchable style={styles.radio} onPress={()=>{handleRadio("image")}}>
          <Text style={formData.type === "image" ? styles.radioItem1 : styles.radioItem}></Text>
          <Text style={styles.label}>图片</Text>
        </Touchable>
        <Touchable style={styles.radio} onPress={()=>{handleRadio("video")}}>
          <Text style={formData.type === "video" ? styles.radioItem1 : styles.radioItem}></Text>
          <Text style={styles.label}>视频</Text>
        </Touchable>
        </View>
        <Touchable onPress={handleAddArtical} style={styles.publishBox}>
          <Text style={styles.publishBtn}>发布文章</Text>
        </Touchable>
      </View>
      </ScrollView>
    </View>
  );
}
const styles = StyleSheet.create({
  addArtical:{
    padding: 10,
    backgroundColor: '#fff',
    width: windowWidth,
    height: windowHeight,
  },
  mainBox: {
    display:"flex",
    alignItems:"center",
    
  },
  bigTitle: {
    fontSize:70,
    fontWeight:"700",
    color:"#A75E5E",
  },
  title: {
    fontSize:16,
    fontWeight:"700",
    fontFamily:"Edwardian Script ITC",
    color:"#A75E5E",
  },
  inputBox: {
    width:getWidth(80),
    height:40,
    borderColor:"#A75E5E",
    borderWidth: 1 / PixelRatio.get(),
  },
  inputBoxTop: {
    marginTop:5
  },
  label:{
    height:30,
    lineHeight:30
  },
  publishBox:{
    height:150,
  },
  publishBtn:{
    width:getWidth(50),
    height:35,
    color:"#fff",
    textAlign:"center",
    backgroundColor:"#A75E5E",
    marginVertical:35,
    borderRadius:35,
    lineHeight:35,
  },
  manyLines:{
    height:200,
    textAlignVertical: 'top'
  },
  addBox:{
    width:getWidth(80),
    display:"flex",
    flexDirection:"row",
  },
  file:{
    width:120,
  },
  addpng:{
    width:100,
    height:100,
  },
  radioBox:{
    width:getWidth(80),
    display:"flex",
    flexDirection:"row",
    justifyContent:"flex-start"
  },
  radio:{
    height:40,
    width:100,
    alignSelf:"flex-end",
    display:"flex",
    flexDirection:"row",
    justifyContent:"center",
    alignItems:"center"
  },
  radioItem:{
    width:15,
    height:15,
    borderRadius:15,
    borderWidth:1 / PixelRatio.get(),
    borderColor:"#A75E5E",
    marginRight:10
  },
  // 点击单选按钮之后切换按钮的背景色
  radioItem1:{
    width:15,
    height:15,
    borderRadius:15,
    backgroundColor:"#A75E5E",
    borderWidth:1 / PixelRatio.get(),
    borderColor:"#A75E5E",
    marginRight:10
  },
  selectImageBox:{
    width:"100%",
  },
  imageBox:{
    width:"100%",
    display:"flex",
    flexDirection:"row",
    flexWrap:"wrap"
  },
  avatarImage: {
    width:92,
    height:92,
    margin:2,
  },
  text:{
    height:30,
    lineHeight:30
  }
})
export default connector(AddArtical);